package com.car.action.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.car.backend.opensource.AlipayConfig;
import com.car.backend.opensource.AlipayRSA;
import com.car.backend.opensource.GetWxOrderno;
import com.car.backend.opensource.HttpUtils;
import com.car.backend.opensource.WeiXinAPPUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.car.action.util.CommonController;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.VipPackage;
import com.car.common.model.VipRecord;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.stonehenge.backend.tools.StaticToolit;
import com.utils.APIJSON;
import com.utils.Sha1Util;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.TenpayUtil;
import com.utils.Toolkit;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

public class OrderController  extends CommonController  {
	
	public void list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			
			Long user_id = super.getUserId();
			MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_ORDER, user_id.intValue());
			int page = 1;
	        if(!StringUtil.empty(getPara("page"))) {
	    	   page = getParaToInt("page");
	        }
	        // and a.status != 2    User用户余额 System系统
	        // and a.buy_type != 'User' 
	        List<VipRecord> result =  VipRecord.dao.find("select a.id,a.title,a.price,a.order_num,a.status, CASE a.status WHEN '1' THEN '已支付' WHEN '3' THEN '支付失败' ELSE '异常' END as status_name,FROM_UNIXTIME(a.create_time,'%Y-%m-%d') as time,u.nick_name as nick_name,tu.nick_name as to_nick_name,tu.id as to_user_id from vip_record as a  left join users u on u.id = a.user_id left join users tu on tu.id = a.target_user_id where a.status = 1 and a.buy_type != 'System' and a.user_id = " + user_id +" order by a.id desc limit " + (page-1)*15 +",15 ");
	        
			renderJson(APIJSON.sendJSON(result));
		}
	}
	
	/**
	 * 下单接口
	 */
	public void plance() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			if (StringUtil.empty(getPara("package_id"))) {
				renderJson(APIJSON.result(4001));
			}
			Long user_id = super.getUserId();
			int order_id = 0;
			String package_id = getPara("package_id");
			VipPackage vipPackage = VipPackage.dao.findById(package_id);
			if (vipPackage != null) {
				if (vipPackage.getType() == 1) {
					VipRecord one = new VipRecord();
					one.setUserId(user_id.intValue());
					one.setOrderNum(Toolkit.newTradeNo());
					one.setTitle(vipPackage.getTitle());
					one.setBuyType("User");
					one.setZsHot(vipPackage.getZsHot());
					one.setTime(Integer.valueOf(vipPackage.getDays()));
					one.setPrice(vipPackage.getPrice());
					one.setStatus(2);
					one.setOrderType(1);
					one.setVipPackageId(vipPackage.getId());
					one.setCreateTime(SystemClock.now()/1000L);
					one.setUpdateTime(SystemClock.now()/1000L);
					if (user_id == 140901L) {
						one.setPrice(new BigDecimal(1));
					}
					one.save();
					order_id = one.getId();
				} else {
					VipRecord one = new VipRecord();
					one.setUserId(user_id.intValue());
					one.setOrderNum(Toolkit.newTradeNo());
					one.setTitle("热度充值" + vipPackage.getTitle());
					one.setBuyType("User");
					one.setZsHot(vipPackage.getZsHot());
					one.setHot(vipPackage.getHot());
					one.setTime(0);
					one.setPrice(vipPackage.getPrice());
					one.setStatus(2);
					one.setOrderType(2);
					one.setVipPackageId(vipPackage.getId());
					one.setCreateTime(SystemClock.now()/1000L);
					one.setUpdateTime(SystemClock.now()/1000L);
					if (user_id == 140901L) {
						one.setPrice(new BigDecimal(1));
					}
					one.save();
					order_id = one.getId();
				}
			}
			
			Map<String,Object> result = Maps.newHashMap();
			result.put("order_id", order_id);
			renderJson(APIJSON.sendJSON(result));
			return;
		}
	}
	
	
	/**
	 * 支付接口
	 */
	public void pay(){
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			if (StringUtil.empty(getPara("order_id"))) {
				renderJson(APIJSON.result(4001));
				return;
			}
			if (StringUtil.empty(getPara("pay_type"))) {
				renderJson(APIJSON.result(1054));
				return;
			}
			String order_id = getPara("order_id");
			
			VipRecord record = VipRecord.dao.findById(order_id);
			if (record == null) {
				renderJson(APIJSON.result(1045));
				return;
			}
			String pay_type = getPara("pay_type");
			String pay_data = "";
			
			if ("AliPay".equalsIgnoreCase(pay_type)) {
				pay_data = alipay(record);
				
			} else if ("WxPay".equalsIgnoreCase(pay_type)) {
				renderJson(APIJSON.sendJSON(wxpay(record,Toolkit.one.getIpAddr(getRequest()))));
				return;
			}
			Map<String,Object> result = Maps.newHashMap();
			result.put("pay_data", pay_data);
			renderJson(APIJSON.sendJSON(result));
			
		}
	}
	
	
	/**
	 * 微信支付
	 * @param record
	 * @return
	 */
	private Map<String,Object> wxpay(VipRecord record,String ip) {
		String appid = WeiXinAPPUtil.APP_ID;
		String mch_id = WeiXinAPPUtil.MCH_ID;

		String currTime = TenpayUtil.getCurrTime();
		String strTime = currTime.substring(8, currTime.length());
		String strRandom = TenpayUtil.buildRandom(4) + "";
		//10位序列号,可以自行调整。
		String nonce_str = strTime + strRandom;

		String body = record.getTitle();
		String out_trade_no = record.getOrderNum();
		BigDecimal total = record.getPrice();
		// 签名
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		parameters.put("appid", appid);
		parameters.put("body", body);
		parameters.put("limit_pay", "no_credit");
		parameters.put("mch_id", mch_id);
		parameters.put("nonce_str", nonce_str);
		parameters.put("notify_url", WeiXinAPPUtil.CALLBACK_URL);
		parameters.put("out_trade_no", out_trade_no);

		parameters.put("spbill_create_ip", ip);
		//System.out.print("total_fee"+(total.multiply(new BigDecimal(100))).intValue());
		parameters.put("total_fee", (total.multiply(new BigDecimal(100))).intValue()+"");
		parameters.put("trade_type", "APP");

		String sign = WeiXinAPPUtil.createSign("UTF-8", parameters);
		parameters.put("sign", sign);

		String requestXML = WeiXinAPPUtil.getRequestXml(parameters);
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

		String prepay_id = new GetWxOrderno().getPayNo(createOrderURL,requestXML);
		if (StaticToolit.isEmpty(prepay_id)) {
			
			//return tidy.putHalfWayOrExceptionReturn(-1, "wx check fail!", "微信校验失败 ");
		}

		SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
		String timestamp = Sha1Util.getTimeStamp();
		String packages = "Sign=WXPay";

		finalpackage.put("appid", appid);
		finalpackage.put("timestamp", timestamp);
		finalpackage.put("noncestr", nonce_str);
		finalpackage.put("package", packages);
		finalpackage.put("prepayid", prepay_id);
		finalpackage.put("partnerid", mch_id);
		String finalsign = WeiXinAPPUtil.createSign("UTF-8",finalpackage);
		Map<String,Object> map = Maps.newHashMap();
		map.put("timestamp", timestamp);
		map.put("noncestr", nonce_str);
		map.put("package", packages);
		map.put("prepayid", prepay_id);
		map.put("paysign", finalsign);
		map.put("partnerid", mch_id);
		return map;
	}

	/*
	  * 支付宝 
	  */
	private String alipay(VipRecord record) {
		String tradeNo = record.getOrderNum();
		String subject = record.getTitle();
		String amount1 = String.valueOf(record.getPrice());
		String  APP_ID = AlipayConfig.app_id;
		String  APP_PRIVATE_KEY = AlipayConfig.alipay_cm_private_key;
		String  CHARSET = "utf-8";
		String  ALIPAY_PUBLIC_KEY  = AlipayConfig.alipay_app_public_key;
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(subject);
		model.setSubject(subject);
		model.setOutTradeNo(tradeNo);
		model.setTimeoutExpress("90m");
		model.setTotalAmount(amount1);
		if (record.getUserId() == 140901L) {
			model.setTotalAmount("0.01");
		}
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl("http://api.50duhui.top/callback/alipay");
		request.setReturnUrl("http://api.50duhui.top/callback/alipay");
		try {
		        //这里和普通的接口调用不同，使用的是sdkExecute
		        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
		        String result = response.getBody();
		        System.out.println(result);//就是orderString 可以直接给客户端请求，无需再做处理。
		        return result;
		} catch (AlipayApiException e) {
		        e.printStackTrace();
		}

		return null;
	}
	

	
	public static void main(String[] args) {
		   
	}
	
}
